#include "StdAfx.h"
#include "VSqlDataMRef.h"

// VSqlDataMRef ///////////////////////////////////////////////////////////////

//
void VSqlDataMRef::createTable(const QSqlDatabase &db,const QString &dataTableName)
{
	Q_ASSERT(dataTableName.isEmpty() == false);
	VSqlDataMRef mRef;
	
	QString sql 
		= "create table " + tableName(dataTableName) + "("
		+		mRef.idRec().name()			+ " bigint,"
		+		mRef.refIdItem().name()	+ " bigint,"
		+		mRef.refIdRec().name()	+ " bigint,"
		+		mRef.pos().name()				+ " integer"
		+ ")";

	if (VSqlLog::canWrite())
		VSqlLog::write("VSqlDataMRef::createTable",sql);

	bool isOk = VSqlQuery(db).exec(sql);
	Q_ASSERT(isOk == true);
}

//
void VSqlDataMRef::deleteRef
(
	const QSqlDatabase &db,
	const QString &dataTableName,
	const QVariantList &idRecList
)
{
	QString sIdRec;
	foreach (const QVariant idRec,idRecList)
		sIdRec += idRec.toString() + ",";

	sIdRec.remove(sIdRec.count()-1,1);

	VSqlDataMRef mRef;
	VSqlQuery_delete del(db);

	del.prepare
	(
		mRef.tableName(dataTableName),
		QString() 
			= mRef.idRec().name() + " in(" + sIdRec + ")"
	);

	if (VSqlLog::canWrite())
		VSqlLog::write("VSqlDataMRef::deleteRef",del.sql());

	del.exec(VSqlFieldList());
}

//
void VSqlDataMRef::deleteRef
(
	const QSqlDatabase &db,
	const QString &dataTableName,
	const QVariant &idRec,
	const QVariant &refIdItem
)
{
	VSqlDataMRef mRef;
	VSqlQuery_delete del(db);

	del.prepare
	(
		mRef.tableName(dataTableName),
		QString() 
			= mRef.idRec().name()     + " = " + idRec.toString() + " and "
			+ mRef.refIdItem().name()	+ " = " + refIdItem.toString()
	);

	if (VSqlLog::canWrite())
		VSqlLog::write("VSqlDataMRef::deleteRef",del.sql());

	del.exec(VSqlFieldList());
}

//
void VSqlDataMRef::insertRef
(
	const QSqlDatabase &db,
	const QString &dataTableName,
	const QVariant &idRec,
	const QVariant &refIdItem,
	const QVariant &refIdRec
)
{
	VSqlDataMRef mRef;
		mRef.setIdRec(idRec);
		mRef.setRefIdItem(refIdItem);
		
	VSqlQuery_insert ins(db);

	ins.prepare
	(
		mRef.tableName(dataTableName),
		mRef.fieldList()
	);

	if (VSqlLog::canWrite())
		VSqlLog::write("VSqlDataMRef::insertRef",ins.sql());

	int pos = 0;
	QStringList refIdRecList = refIdRec.toString().split(",");

	foreach (const QString v,refIdRecList)
	{
		mRef.setRefIdRec(v);
		mRef.setPos(pos++);
		
		ins.exec
		(
			mRef.idRec(),
			mRef.fieldPtrList()
		);
	}
}
